package com.eet.elasticsearch.service.impl;

import com.alibaba.fastjson.JSON;
import com.eet.elasticsearch.constants.CommonConstants;
import com.eet.elasticsearch.entity.JdContentDto;
import com.eet.elasticsearch.service.ContentService;
import com.eet.elasticsearch.utils.HtmlParseUtil;
import io.netty.util.internal.StringUtil;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 业务实现类
 *
 * @author zheng.zhang
 */
@Service
public class ContentServiceImpl implements ContentService {
    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Override
    public Boolean addBatchContent(String keyword) throws IOException {
        List<JdContentDto> contents = HtmlParseUtil.parseJd(keyword);
        // 把查询到的结果放入ES中
        BulkRequest request = new BulkRequest();
        request.timeout(TimeValue.timeValueMinutes(2));

        for (JdContentDto content : contents) {
            request.add(new IndexRequest(CommonConstants.ES_GOODS_INDEX).source(JSON.toJSONString(content), XContentType.JSON));
        }
        BulkResponse bulk = restHighLevelClient.bulk(request, RequestOptions.DEFAULT);
        return !bulk.hasFailures();
    }

    @Override
    public List<Map<String, Object>> searchContent(String keywords, Integer pageNo, Integer pageSize) throws IOException {
        List<Map<String, Object>> contents = new ArrayList<>();
        if (pageNo < 1 || pageSize < 1) {
            return contents;
        }
        // 条件搜索
        SearchRequest searchRequest = new SearchRequest(CommonConstants.ES_GOODS_INDEX);
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

        // 分页
        sourceBuilder.from(pageNo);
        sourceBuilder.size(pageSize);

        // 精确匹配
        TermQueryBuilder builder = QueryBuilders.termQuery(CommonConstants.TITLE, keywords);
        sourceBuilder.query(builder);
        sourceBuilder.timeout(TimeValue.timeValueMinutes(1));

        // 关键词高亮显示
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field(CommonConstants.TITLE);
        // 关闭多个高亮显示
        highlightBuilder.requireFieldMatch(false);
        highlightBuilder.preTags("<span style='color: red;'>");
        highlightBuilder.postTags("</span>");
        sourceBuilder.highlighter(highlightBuilder);

        // 执行搜索
        searchRequest.source(sourceBuilder);
        SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

        // 解析结果
        for (SearchHit hit : response.getHits().getHits()) {
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            HighlightField title = highlightFields.get(CommonConstants.TITLE);
            // 原本的结果
            Map<String, Object> sourceAsMap = hit.getSourceAsMap();
            // 解析高亮的结果,将高亮结果替换原本结果
            if (title!=null) {
                Text[] fragments = title.fragments();
                StringBuilder temp = new StringBuilder(StringUtil.EMPTY_STRING);
                for (Text fragment : fragments) {
                    temp.append(fragment);
                }
                sourceAsMap.put(CommonConstants.TITLE, temp.toString());
            }
            contents.add(sourceAsMap);
        }
        return contents;
    }
}
